<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\scanwork\Config as ConfigModel;
use think\Db;
use think\Request;
use Exception;

class Userex extends Api
{
    protected $noNeedLogin = ['login', 'autoLogin', 'test', 'dbTest', 'uploadImage'];
    protected $noNeedRight = ['*'];

    /**
     * 重写初始化方法，支持Bearer token
     */
    protected function _initialize()
    {
        // 支持Bearer token格式
        $authorization = $this->request->header('Authorization');
        if ($authorization && strpos($authorization, 'Bearer ') === 0) {
            $token = substr($authorization, 7); // 去掉 'Bearer ' 前缀
            $this->request->server(['HTTP_TOKEN' => $token]);
        }
        
        // 调用父类初始化
        parent::_initialize();
    }

    /**
     * 测试接口
     */
    public function test()
    {
        try {
            // 检查数据库连接
            $result = [];
            
            // 记录错误信息
            error_log('test - starting database check');
            
            // 检查表是否存在
            $tables = ['scanwork_allocation', 'scanwork_report', 'scanwork_order', 'scanwork_model', 'scanwork_product', 'scanwork_process'];
            foreach ($tables as $table) {
                try {
                    $exists = Db::query("SHOW TABLES LIKE '{$table}'");
                    $result[$table] = !empty($exists);
                    error_log("test - table {$table}: " . ($result[$table] ? 'exists' : 'not exists'));
                } catch (Exception $e) {
                    error_log("test - error checking table {$table}: " . $e->getMessage());
                    $result[$table] = false;
                }
            }
            
            // 检查各表的数据量
            if ($result['scanwork_allocation']) {
                try {
                    $result['allocation_count'] = Db::name('scanwork_allocation')->count();
                    error_log("test - allocation_count: " . $result['allocation_count']);
                } catch (Exception $e) {
                    error_log("test - error counting allocations: " . $e->getMessage());
                    $result['allocation_count'] = 'error';
                }
            }
            if ($result['scanwork_report']) {
                try {
                    $result['report_count'] = Db::name('scanwork_report')->count();
                    error_log("test - report_count: " . $result['report_count']);
                } catch (Exception $e) {
                    error_log("test - error counting reports: " . $e->getMessage());
                    $result['report_count'] = 'error';
                }
            }
            if ($result['scanwork_order']) {
                try {
                    $result['order_count'] = Db::name('scanwork_order')->count();
                    error_log("test - order_count: " . $result['order_count']);
                } catch (Exception $e) {
                    error_log("test - error counting orders: " . $e->getMessage());
                    $result['order_count'] = 'error';
                }
            }
            
            // 检查当前登录用户
            try {
                if ($this->auth->isLogin()) {
                    $user = $this->auth->getUserinfo();
                    $result['current_user'] = $user;
                    error_log("test - current_user: " . json_encode($user));
                    
                    if ($result['scanwork_allocation']) {
                        try {
                            $result['user_allocations'] = Db::name('scanwork_allocation')->where('user_id', $user['id'])->count();
                            error_log("test - user_allocations: " . $result['user_allocations']);
                        } catch (Exception $e) {
                            error_log("test - error counting user allocations: " . $e->getMessage());
                            $result['user_allocations'] = 'error';
                        }
                    }
                } else {
                    $result['current_user'] = 'not_login';
                    error_log("test - user not logged in");
                }
            } catch (Exception $e) {
                error_log("test - error checking user: " . $e->getMessage());
                $result['current_user'] = 'error: ' . $e->getMessage();
            }
            
            error_log("test - final result: " . json_encode($result));
            $this->success('数据库检查完成', $result);
        } catch (Exception $e) {
            error_log("test - main error: " . $e->getMessage());
            $this->error('数据库检查失败：' . $e->getMessage());
        }
    }

    /**
     * 数据库连接测试
     */
    public function dbTest()
    {
        try {
            // 测试基本数据库连接
            $result = [];
            
            // 获取数据库配置
            $config = config('database');
            $result['database_config'] = [
                'hostname' => $config['hostname'],
                'database' => $config['database'],
                'username' => $config['username'],
                'hostport' => $config['hostport']
            ];
            
            // 测试简单查询
            $testQuery = Db::query("SELECT 1 as test");
            $result['simple_query'] = $testQuery;
            
            // 获取所有表
            $tables = Db::query("SHOW TABLES");
            $result['all_tables'] = $tables;
            
            // 检查scanwork相关表
            $scanworkTables = Db::query("SHOW TABLES LIKE 'scanwork_%'");
            $result['scanwork_tables'] = $scanworkTables;
            
            $this->success('数据库连接测试完成', $result);
        } catch (Exception $e) {
            $this->error('数据库连接测试失败：' . $e->getMessage());
        }
    }

    /**
     * 上传报工图片
     */
    public function uploadImage()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $itemNo = $this->request->post('item_no', ''); // 产品编号
        $reportId = $this->request->post('report_id', 0); // 报工ID
        
        if (!empty($_FILES['file'])) {
            $file = $_FILES['file'];
            
            if ($file['error'] == 0) {
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                $allowExt = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'jfif'];
                if (!in_array(strtolower($ext), $allowExt)) {
                    $this->error('不支持的文件格式');
                }
                
                if ($file['size'] > 10 * 1024 * 1024) {
                    $this->error('文件大小不能超过10MB');
                }
                
                $filename = uniqid() . '_' . ($itemNo ?: 'report') . '.' . $ext;
                $dateDir = date('Y-m-d');
                $uploadDir = 'uploads/baogong/' . $dateDir . '/';
                
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $filepath = $uploadDir . $filename;
                
                if (move_uploaded_file($file['tmp_name'], $filepath)) {
                    $imageUrl = '/uploads/baogong/' . $dateDir . '/' . $filename;
                    
                    // 如果有报工ID，直接保存图片记录
                    if ($reportId > 0 && !empty($itemNo)) {
                        try {
                            $item = Db::name('scanwork_product_item')
                                ->where('item_no', $itemNo)
                                ->find();
                            
                            if ($item) {
                                Db::name('scanwork_item_report_image')->insert([
                                    'item_id' => $item['id'],
                                    'report_id' => $reportId,
                                    'image_url' => $imageUrl,
                                    'upload_user_id' => $user['id'],
                                    'createtime' => time()
                                ]);
                            }
                        } catch (\Exception $e) {
                            // 记录错误但不影响上传
                            error_log('保存图片记录失败: ' . $e->getMessage());
                        }
                    }
                    
                    $this->success('上传成功', [
                        'url' => $imageUrl
                    ]);
                } else {
                    $this->error('文件上传失败');
                }
            } else {
                $this->error('文件上传错误');
            }
        } else {
            $this->error('没有选择文件');
        }
    }

    /**
     * 小程序自动登录
     */
    public function autoLogin()
    {
        $code = $this->request->post('code');
        if (!$code) {
            $this->error('缺少微信授权码');
        }

        // 微信小程序配置
        $appid = ConfigModel::getMiniappAppid();
        $secret = ConfigModel::getMiniappSecret();
        
        // 获取微信openid
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $result = file_get_contents($url);
        $data = json_decode($result, true);
        
        if (isset($data['errcode'])) {
            $this->error('微信授权失败：' . $data['errmsg']);
        }
        
        $openid = $data['openid'];
        $session_key = $data['session_key'];
        
        // 查找或创建用户
        $user = Db::name('user')->where('openid', $openid)->find();
        
        if (!$user) {
            // 创建新用户
            $userData = [
                'username' => 'wx_' . substr($openid, -8),
                'nickname' => '微信用户',
                'openid' => $openid,
                'avatar' => '',
                'createtime' => time(),
                'status' => 'normal'
            ];
            $userId = Db::name('user')->insertGetId($userData);
            $user = Db::name('user')->where('id', $userId)->find();
        }
        
        // 生成token
        $token = \fast\Random::alnum(32);
        \app\common\library\Token::set($token, $user['id']);
        
        $this->success('登录成功', [
            'token' => $token,
            'user' => $user
        ]);
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        
        // 调试信息
        error_log('getUserInfo - user: ' . json_encode($user));
        
        $this->success('获取成功', $user);
    }

    /**
     * 修改用户信息
     */
    public function updateUserInfo()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $password = $this->request->post('password');
        
        $updateData = [];
        
        if ($username) {
            // 检查用户名是否已经修改过（通过检查是否以wx_开头）
            $currentUser = Db::name('user')->where('id', $user['id'])->find();
            if ($currentUser && !str_starts_with($currentUser['username'], 'wx_')) {
                $this->error('用户名只能修改一次');
            }
            
            // 检查用户名是否已存在
            $exists = Db::name('user')->where('username', $username)->where('id', '<>', $user['id'])->find();
            if ($exists) {
                $this->error('用户名已存在');
            }
            $updateData['username'] = $username;
        }
        
        if ($nickname) {
            $updateData['nickname'] = $nickname;
        }
        
        if ($email) {
            // 验证邮箱格式
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $this->error('邮箱格式不正确');
            }
            // 检查邮箱是否已存在
            $exists = Db::name('user')->where('email', $email)->where('id', '<>', $user['id'])->find();
            if ($exists) {
                $this->error('邮箱已被使用');
            }
            $updateData['email'] = $email;
        }
        
        if ($mobile) {
            // 验证手机号格式
            if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
                $this->error('手机号格式不正确');
            }
            // 检查手机号是否已存在
            $exists = Db::name('user')->where('mobile', $mobile)->where('id', '<>', $user['id'])->find();
            if ($exists) {
                $this->error('手机号已被使用');
            }
            $updateData['mobile'] = $mobile;
        }
        
        if ($password) {
            // 验证密码长度
            if (strlen($password) < 6) {
                $this->error('密码长度不能少于6位');
            }
            // 生成新的salt
            $salt = \fast\Random::alnum();
            $updateData['password'] = md5(md5($password) . $salt);
            $updateData['salt'] = $salt;
        }
        
        if (empty($updateData)) {
            $this->error('没有要更新的数据');
        }
        
        $result = Db::name('user')->where('id', $user['id'])->update($updateData);
        
        if ($result) {
            $this->success('更新成功');
        } else {
            $this->error('更新失败');
        }
    }

    /**
     * 个人中心
     */
    public function profile()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        
        // 获取完整的用户信息
        $fullUser = Db::name('user')->where('id', $user['id'])->find();
        
        // 格式化时间
        if ($fullUser) {
            $fullUser['jointime'] = $fullUser['jointime'] ? date('Y-m-d H:i:s', $fullUser['jointime']) : '';
            $fullUser['logintime'] = $fullUser['logintime'] ? date('Y-m-d H:i:s', $fullUser['logintime']) : '';
            $fullUser['createtime'] = $fullUser['createtime'] ? date('Y-m-d H:i:s', $fullUser['createtime']) : '';
        }
        
        // 获取统计数据
        $userId = $user['id'];
        $today = date('Y-m-d');
        $startTime = strtotime($today . ' 00:00:00');
        $endTime = strtotime($today . ' 23:59:59');
        
        // 今日任务数
        $todayTaskCount = Db::name('scanwork_allocation')
            ->where('user_id', $userId)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->count();
        
        // 今日报工数
        $todayReportCount = Db::name('scanwork_report')
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->sum('quantity');
        
        // 今日工资
        $todayWage = Db::name('scanwork_report')
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->sum('wage');
        
        // 总统计数据
        $totalTasks = Db::name('scanwork_allocation')->where('user_id', $userId)->count();
        $totalReports = Db::name('scanwork_report')->where('user_id', $userId)->count();
        $totalWage = Db::name('scanwork_report')->where('user_id', $userId)->where('status', 1)->sum('wage');
        
        $this->success('获取成功', [
            'user' => $fullUser ?: $user,
            'todayTaskCount' => $todayTaskCount,
            'todayReportCount' => $todayReportCount,
            'todayWage' => $todayWage ?: 0,
            'totalTasks' => $totalTasks,
            'totalReports' => $totalReports,
            'totalWage' => $totalWage ?: 0
        ]);
    }

    /**
     * 获取任务列表
     */
    public function getTasks()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $workerId = $user['id'];
        
        $tasks = Db::name('scanwork_allocation')
            ->alias('a')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('a.user_id', $workerId)
            ->where('a.status', 0)
            ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->order('a.createtime desc')
            ->select();
        
        $this->success('获取成功', $tasks);
    }

    /**
     * 获取报工页面数据
     */
    public function getReportData()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $allocationId = $this->request->param('allocation_id') ?: $this->request->param('id');
        
        if (!$allocationId) {
            $this->error('未指定任务ID');
        }
        
        $allocation = Db::name('scanwork_allocation')
            ->alias('a')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('a.id', $allocationId)
            ->where('a.user_id', $user['id'])
            ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->find();
        
        if (!$allocation) {
            $this->error('任务不存在或不属于当前用户');
        }
        
        // 获取可报工的产品编号
        $productItems = Db::name('scanwork_product_item')
            ->where('allocation_id', $allocationId)
            ->where('status', 0) // 未报工状态
            ->order('item_no')
            ->select();
        
        // 计算已报数量和待报数量
        $reportedQuantity = Db::name('scanwork_report')
            ->where('allocation_id', $allocationId)
            ->where('status', 1)
            ->sum('quantity');
        
        $allocation['reported_quantity'] = intval($reportedQuantity);
        $allocation['remaining_quantity'] = max(0, $allocation['quantity'] - $allocation['reported_quantity']);
        $allocation['product_items'] = $productItems;
        
        $this->success('获取成功', $allocation);
    }

    /**
     * 提交报工
     */
    public function submitReport()
    {
        error_log("=== 小程序报工开始 ===");
        
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $workerId = $user['id'];
        
        error_log("小程序报工 - 用户ID: " . $workerId);
        
        // 获取参数
        $allocationId = intval($this->request->post('allocation_id', 0));
        $itemNos = $this->request->post('item_nos/a', []); // 产品编号数组，使用/a确保是数组
        $workType = $this->request->post('work_type', 'piece');
        $workHours = floatval($this->request->post('work_hours', 0));
        $remark = $this->request->post('remark', '');
        $imageUrls = $this->request->post('image_urls/a', []); // 图片URL数组，使用/a确保是数组
        
        error_log("小程序报工 - 参数: allocation_id=$allocationId, item_nos=" . json_encode($itemNos) . ", work_type=$workType, work_hours=$workHours");
        error_log("小程序报工 - image_urls类型: " . gettype($imageUrls));
        error_log("小程序报工 - image_urls内容: " . json_encode($imageUrls));
        
        // 确保image_urls是数组
        if (!is_array($imageUrls)) {
            if (is_string($imageUrls)) {
                $decoded = json_decode($imageUrls, true);
                if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                    $imageUrls = $decoded;
                } else {
                    $imageUrls = [];
                }
            } else {
                $imageUrls = [];
            }
        }
        
        error_log("小程序报工 - 处理后的图片数量: " . count($imageUrls));
        
        // 验证参数
        if (empty($allocationId)) {
            $this->error('分工ID不能为空');
        }
        
        if ($workType == 'piece' && empty($itemNos)) {
            $this->error('产品编号不能为空');
        }
        
        if ($workType == 'time' && empty($workHours)) {
            $this->error('工时不能为空');
        }
        
        try {
            // 验证分工是否存在且属于当前用户
            $allocation = Db::name('scanwork_allocation')->where('id', $allocationId)->find();
            if (!$allocation) {
                $this->error('分工不存在');
            }
            
            if ($allocation['user_id'] != $workerId) {
                $this->error('无权操作此分工');
            }
            
            error_log("小程序报工 - 分工验证通过");
            
            // 如果是计件工作，验证产品编号
            if ($workType == 'piece') {
                foreach ($itemNos as $itemNo) {
                    $item = Db::name('scanwork_product_item')
                        ->where('allocation_id', $allocationId)
                        ->where('item_no', $itemNo)
                        ->find();
                    
                    if (!$item) {
                        $this->error('产品编号不存在: ' . $itemNo);
                    }
                    
                    if ($item['status'] != 0) {
                        $this->error('该产品编号已报工: ' . $itemNo);
                    }
                }
                
                error_log("小程序报工 - 产品编号验证通过");
            }
            
            Db::startTrans();
            
            try {
                // 创建报工记录
                $reportData = [
                    'allocation_id' => $allocationId,
                    'user_id' => $workerId,
                    'type' => $workType,
                    'quantity' => $workType == 'piece' ? count($itemNos) : $workHours,
                    'item_nos' => $workType == 'piece' ? json_encode($itemNos) : '',
                    'work_hours' => $workType == 'time' ? $workHours : null,
                    'remark' => $remark,
                    'status' => 0,
                    'wage' => 0,
                    'report_time' => time(),
                    'createtime' => time(),
                    'updatetime' => time()
                ];
                
                $reportId = Db::name('scanwork_report')->insertGetId($reportData);
                error_log("小程序报工 - 报工记录创建成功，ID: " . $reportId);
                
                // 如果是计件工作，更新产品编号状态
                if ($workType == 'piece') {
                    foreach ($itemNos as $itemNo) {
                        Db::name('scanwork_product_item')
                            ->where('allocation_id', $allocationId)
                            ->where('item_no', $itemNo)
                            ->update([
                                'status' => 1,
                                'report_id' => $reportId,
                                'updatetime' => time()
                            ]);
                    }
                    
                    error_log("小程序报工 - 产品编号状态更新成功");
                    
                    // 保存图片
                    if (!empty($imageUrls) && is_array($imageUrls)) {
                        foreach ($imageUrls as $imageUrl) {
                            try {
                                // 使用原生SQL避免ThinkPHP Db类的问题
                                $sql = "INSERT INTO fa_scanwork_item_report_image (item_id, report_id, image_url, upload_user_id, createtime) VALUES (?, ?, ?, ?, ?)";
                                $stmt = Db::getPdo()->prepare($sql);
                                
                                // 获取第一个产品编号的item_id
                                $firstItem = Db::name('scanwork_product_item')
                                    ->where('allocation_id', $allocationId)
                                    ->where('item_no', $itemNos[0])
                                    ->find();
                                
                                if ($firstItem) {
                                    $result = $stmt->execute([
                                        $firstItem['id'],
                                        $reportId,
                                        $imageUrl,
                                        $workerId,
                                        time()
                                    ]);
                                    
                                    if ($result) {
                                        error_log("小程序报工 - 图片记录保存成功: " . $imageUrl);
                                    } else {
                                        error_log("小程序报工 - 图片记录保存失败: " . $imageUrl);
                                    }
                                }
                            } catch (\Exception $e) {
                                error_log("小程序报工 - 图片保存失败: " . $e->getMessage());
                                // 不抛出异常，继续执行
                            }
                        }
                        error_log("小程序报工 - 图片保存完成，数量: " . count($imageUrls));
                    }
                }
                
                // 更新分工的已报数量
                Db::name('scanwork_allocation')
                    ->where('id', $allocationId)
                    ->setInc('reported_quantity', $workType == 'piece' ? count($itemNos) : $workHours);
                
                Db::commit();
                error_log("小程序报工 - 提交成功");
                error_log("小程序报工 - 准备返回成功响应");
                
                $response = [
                    'report_id' => $reportId,
                    'item_no' => $itemNos[0] // 返回第一个产品编号，与工作的小程序保持一致
                ];
                
                error_log("小程序报工 - 响应数据: " . json_encode($response));
                
                // 直接返回，不使用success方法
                $result = [
                    'code' => 1,
                    'msg' => '报工成功',
                    'time' => time(),
                    'data' => $response
                ];
                
                error_log("小程序报工 - 最终响应: " . json_encode($result));
                return json($result);
                
            } catch (\Exception $e) {
                Db::rollback();
                error_log("小程序报工失败 - 数据库异常: " . $e->getMessage());
                $this->error('报工失败：' . $e->getMessage());
            }
            
        } catch (\Exception $e) {
            error_log("小程序报工失败 - 验证异常: " . $e->getMessage());
            $this->error('报工失败：' . $e->getMessage());
        }
    }

    /**
     * 扫码报工
     */
    public function scanReport()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $workerId = $this->auth->id;
        $qrCode = $this->request->post('qr_code');
        
        if (!$qrCode) {
            $this->error('二维码数据不能为空');
        }
        
        // 解析二维码数据（格式：allocation_id）
        $allocationId = $qrCode;
        
        // 验证分配记录
        $allocation = Db::name('scanwork_allocation')
            ->alias('a')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('a.id', $allocationId)
            ->where('a.user_id', $workerId)
            ->where('a.status', 0)
            ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->find();
        
        if (!$allocation) {
            $this->error('无效的二维码或任务已完成');
        }
        
        // 计算剩余数量
        $reportedQuantity = Db::name('scanwork_report')
            ->where('allocation_id', $allocationId)
            ->where('status', 1)
            ->sum('quantity');
        
        $remainingQuantity = max(0, $allocation['quantity'] - $reportedQuantity);
        
        if ($remainingQuantity <= 0) {
            $this->error('该任务已无待报数量');
        }
        
        $allocation['remaining_quantity'] = $remainingQuantity;
        $this->success('扫码成功', $allocation);
    }

    /**
     * 获取报工记录
     */
    public function getRecords()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        
        $records = Db::name('scanwork_report')
            ->where('user_id', $user['id'])
            ->order('createtime desc')
            ->select();
        
        // 为每条记录补充详细信息
        foreach ($records as &$record) {
            $allocation = Db::name('scanwork_allocation')->where('id', $record['allocation_id'])->find();
            
            if ($allocation) {
                $order = Db::name('scanwork_order')->where('id', $allocation['order_id'])->find();
                $record['order_no'] = $order ? $order['order_no'] : '';
                
                $model = Db::name('scanwork_model')->where('id', $allocation['model_id'])->find();
                $record['model_name'] = $model ? $model['name'] : '';
                
                if ($model) {
                    $product = Db::name('scanwork_product')->where('id', $model['product_id'])->find();
                    $record['product_name'] = $product ? $product['name'] : '';
                } else {
                    $record['product_name'] = '';
                }
                
                $process = Db::name('scanwork_process')->where('id', $allocation['process_id'])->find();
                $record['process_name'] = $process ? $process['name'] : '';
            } else {
                $record['order_no'] = '';
                $record['model_name'] = '';
                $record['product_name'] = '';
                $record['process_name'] = '';
            }
            
            // 格式化时间
            $record['createtime_text'] = date('Y-m-d H:i:s', $record['createtime']);
            $record['status_text'] = $record['status'] == 1 ? '已确认' : '待确认';
        }
        
        $this->success('获取成功', [
            'list' => $records,
            'total' => count($records),
            'page' => 1,
            'limit' => count($records)
        ]);
    }

    /**
     * 获取工资统计
     */
    public function getWageStats()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $month = $this->request->param('month', date('Y-m'));
        
        $startTime = strtotime($month . '-01 00:00:00');
        $endTime = strtotime($month . '-' . date('t', $startTime) . ' 23:59:59');
        
        $wages = Db::name('scanwork_report')
            ->alias('r')
            ->join('scanwork_allocation a', 'r.allocation_id = a.id')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('r.user_id', $user['id'])
            ->where('r.status', 1)
            ->where('r.createtime', 'between', [$startTime, $endTime])
            ->field('r.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->order('r.createtime desc')
            ->select();
        
        $totalWage = array_sum(array_column($wages, 'wage'));
        
        $this->success('获取成功', [
            'reports' => $wages,
            'total_quantity' => array_sum(array_column($wages, 'quantity')),
            'total_wage' => $totalWage,
            'start_date' => date('Y-m-01', $startTime),
            'end_date' => date('Y-m-d', $endTime)
        ]);
    }

    /**
     * 获取统计图表数据
     */
    public function getStats()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $workerId = $this->auth->id;
        
        // 获取最近7天的数据
        $dates = [];
        $quantities = [];
        $wages = [];
        
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-{$i} days"));
            $dates[] = $date;
            
            $quantity = Db::name('scanwork_report')
                ->where('user_id', $workerId)
                ->where('status', 1)
                ->where('createtime', 'between', [strtotime($date), strtotime($date . ' 23:59:59')])
                ->sum('quantity');
            
            $wage = Db::name('scanwork_report')
                ->where('user_id', $workerId)
                ->where('status', 1)
                ->where('createtime', 'between', [strtotime($date), strtotime($date . ' 23:59:59')])
                ->sum('wage');
            
            $quantities[] = intval($quantity);
            $wages[] = floatval($wage);
        }
        
        $this->success('获取成功', [
            'dates' => $dates,
            'quantities' => $quantities,
            'wages' => $wages
        ]);
    }

    /**
     * 获取计时任务列表
     */
    public function getTimeTasks()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        try {
            $workerId = $this->auth->id;
            $tasks = Db::name('scanwork_tallocationtime')
                ->where('user_id', $workerId)
                ->where('status', 0)
                ->order('work_date desc')
                ->select();
            
            foreach ($tasks as &$task) {
                $task['work_date_text'] = date('Y-m-d', strtotime($task['work_date']));
            }
            
            $this->success('获取成功', $tasks);
        } catch (Exception $e) {
            $this->error('获取计时任务失败：' . $e->getMessage());
        }
    }

    /**
     * 提交计时报工
     */
    public function submitTimeReport()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $workerId = $this->auth->id;
        
        if ($this->request->isPost()) {
            try {
                $tallocationtime_id = $this->request->post('tallocationtime_id');
                $work_date = $this->request->post('work_date');
                $start_time = $this->request->post('start_time');
                $end_time = $this->request->post('end_time');
                $total_hours = floatval($this->request->post('total_hours'));
                $remark = $this->request->post('remark');
                
                if (!$tallocationtime_id || !$work_date || $total_hours <= 0) {
                    $this->error('参数不完整');
                }
                
                // 查找分工任务
                $tallocation = Db::name('scanwork_tallocationtime')->where('id', $tallocationtime_id)->find();
                if (!$tallocation) {
                    $this->error('分工任务不存在');
                }
                
                // 查找工序工时单价
                $processPrice = Db::name('scanwork_process_price')->where([
                    'model_id' => $tallocation['model_id'],
                    'process_id' => $tallocation['process_id']
                ])->find();
                
                if (!$processPrice) {
                    $this->error('工序工价记录未找到');
                }
                
                $time_price = floatval($processPrice['time_price']);
                if ($time_price <= 0) {
                    $this->error('工序工资未设置');
                }
                
                $wage = round($total_hours * $time_price, 2);
                
                Db::startTrans();
                Db::name('scanwork_treporttime')->insert([
                    'tallocationtime_id' => $tallocationtime_id,
                    'user_id' => $workerId,
                    'work_date' => $work_date,
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                    'total_hours' => $total_hours,
                    'wage' => $wage,
                    'remark' => $remark,
                    'status' => 0, // 待确认
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
                Db::commit();
                
                $this->success('计时报工提交成功，等待审核');
                
            } catch (Exception $e) {
                Db::rollback();
                $this->error('计时报工提交失败：' . $e->getMessage());
            }
        }
        
        $this->error('请求方式错误');
    }

    /**
     * 获取计时报工记录
     */
    public function getTimeRecords()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        try {
            $workerId = $this->auth->id;
            $records = Db::name('scanwork_treporttime')
                ->where('user_id', $workerId)
                ->order('work_date desc')
                ->select();
            
            foreach ($records as &$record) {
                $record['work_date_text'] = date('Y-m-d', strtotime($record['work_date']));
                $record['createtime_text'] = date('Y-m-d H:i:s', $record['createtime']);
                $record['status_text'] = $record['status'] == 1 ? '已确认' : '待确认';
            }
            
            $this->success('获取成功', $records);
        } catch (Exception $e) {
            $this->error('获取计时报工记录失败：' . $e->getMessage());
        }
    }

    /**
     * 获取计时工资统计
     */
    public function getTimeWage()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        try {
            $workerId = $this->auth->id;
            $wages = Db::name('scanwork_twage')
                ->where('user_id', $workerId)
                ->order('work_date desc')
                ->select();
            
            foreach ($wages as &$wage) {
                $wage['work_date_text'] = date('Y-m-d', strtotime($wage['work_date']));
            }
            
            $this->success('获取成功', $wages);
        } catch (Exception $e) {
            $this->error('获取计时工资统计失败：' . $e->getMessage());
        }
    }

    /**
     * 主动报工
     */
    public function activeReport()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $workerId = $this->auth->id;
        
        if ($this->request->isPost()) {
            try {
                Db::startTrans();
                
                $order_id = $this->request->post('order_id');
                $order_model = $this->request->post('order_model'); // 格式：model_id:process_id
                $quantity = intval($this->request->post('quantity'));
                $work_hours = floatval($this->request->post('work_hours'));
                $start_time = $this->request->post('start_time');
                $end_time = $this->request->post('end_time');
                $work_date = $this->request->post('work_date');
                $remark = $this->request->post('remark');
                $product_items = $this->request->post('product_items/a'); // 产品编号和图片数据
                $images = $this->request->post('images/a'); // 通用图片数据
                
                // 解析产品型号和工序ID
                $model_process = explode(':', $order_model);
                $model_id = $model_process[0];
                $process_id = $model_process[1];
                
                if (!$order_id || !$model_id || !$process_id || !$work_date) {
                    $this->error('请填写完整信息');
                }
                
                if ($quantity <= 0) {
                    $this->error('数量必须大于0');
                }
                
                if ($work_hours <= 0) {
                    $this->error('工作时长必须大于0');
                }
                
                // 验证订单是否存在
                $order = Db::name('scanwork_order')->where('id', $order_id)->find();
                if (!$order) {
                    $this->error('订单不存在');
                }
                
                // 验证产品型号是否存在
                $model = Db::name('scanwork_model')->where('id', $model_id)->find();
                if (!$model) {
                    $this->error('产品型号不存在');
                }
                
                // 验证工序是否存在
                $process = Db::name('scanwork_process')->where('id', $process_id)->find();
                if (!$process) {
                    $this->error('工序不存在');
                }
                
                // 查找工价
                $processPrice = Db::name('scanwork_process_price')->where([
                    'model_id' => $model_id,
                    'process_id' => $process_id
                ])->find();
                
                if (!$processPrice) {
                    $this->error('该产品型号和工序的工价未设置');
                }
                
                // 计算计件工资
                $piece_wage = round($quantity * $processPrice['price'], 2);
                
                // 计算计时工资
                $time_wage = round($work_hours * $processPrice['time_price'], 2);
                
                // 总工资 = 计件工资 + 计时工资
                $total_wage = $piece_wage + $time_wage;
                
                // 创建主动报工记录
                $activeReportId = Db::name('scanwork_active_report')->insertGetId([
                    'order_id' => $order_id,
                    'product_id' => $model['product_id'],
                    'model_id' => $model_id,
                    'process_id' => $process_id,
                    'user_id' => $workerId,
                    'quantity' => $quantity,
                    'work_hours' => $work_hours,
                    'start_time' => $start_time ?: '',
                    'end_time' => $end_time ?: '',
                    'piece_wage' => $piece_wage,
                    'time_wage' => $time_wage,
                    'total_wage' => $total_wage,
                    'work_date' => $work_date,
                    'remark' => $remark,
                    'status' => 0, // 待审核
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
                
                // 保存产品编号和图片数据（计件图片）
                if (!empty($product_items) && is_array($product_items)) {
                    foreach ($product_items as $item) {
                        $item_no = $item['item_no'];
                        $item_images = $item['images'];
                        
                        // 为每个图片创建记录
                        foreach ($item_images as $image_url) {
                            Db::name('scanwork_active_report_product_item')->insert([
                                'active_report_id' => $activeReportId,
                                'item_no' => $item_no,
                                'image_url' => $image_url,
                                'createtime' => time()
                            ]);
                        }
                    }
                }
                
                // 保存通用图片数据（计时图片）
                if (!empty($images) && is_array($images)) {
                    foreach ($images as $image_url) {
                        Db::name('scanwork_active_report_image')->insert([
                            'active_report_id' => $activeReportId,
                            'image_url' => $image_url,
                            'image_type' => 1, // 员工上传的图片
                            'createtime' => time()
                        ]);
                    }
                }
                
                Db::commit();
                return json(['code' => 1, 'msg' => '主动报工提交成功，等待审核']);
                
            } catch (Exception $e) {
                Db::rollback();
                return json(['code' => 0, 'msg' => '主动报工提交失败：' . $e->getMessage()]);
            }
        }
        
        return json(['code' => 0, 'msg' => '请求方式错误']);
    }

    /**
     * 获取订单列表
     */
    public function getOrders()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $orders = Db::name('scanwork_order')
            ->order('createtime desc')
            ->select();
        
        foreach ($orders as &$order) {
            $order['createtime_text'] = date('Y-m-d H:i:s', $order['createtime']);
        }
        
        $this->success('获取成功', $orders);
    }

    /**
     * 获取产品型号列表
     */
    public function getModels()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        try {
            $models = Db::name('scanwork_model')
                ->alias('m')
                ->join('scanwork_product p', 'm.product_id = p.id')
                ->field('m.id, m.name, p.name as product_name')
                ->order('p.name, m.name')
                ->select();
            
            $this->success('获取成功', $models);
        } catch (Exception $e) {
            $this->error('获取产品型号列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取工序列表
     */
    public function getProcesses()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        try {
            $processes = Db::name('scanwork_process')
                ->where('status', 1)
                ->order('name')
                ->select();
            
            $this->success('获取成功', $processes);
        } catch (Exception $e) {
            $this->error('获取工序列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取订单型号
     */
        public function getOrderModels()
    {
        // 暂时移除登录检查，用于测试
        // if (!$this->auth->isLogin()) {
        //     $this->error('未登录', null, 401);
        // }
        
        $orderId = $this->request->get('order_id');
        error_log("getOrderModels - orderId: " . $orderId);
        
        if (!$orderId) {
            $this->error('参数错误');
        }

        try {
            error_log("getOrderModels - 开始查询订单型号，orderId: " . $orderId);
            
            // 先测试基本查询
            $orderModels = Db::name('scanwork_order_model')
                ->where('order_id', $orderId)
                ->select();
            
            error_log("getOrderModels - 基本查询到订单型号数量: " . count($orderModels));
            
            if (empty($orderModels)) {
                error_log("getOrderModels - 没有找到订单型号，返回空数组");
                return json(['code' => 1, 'msg' => '获取成功', 'data' => []]);
            }
            
            error_log("getOrderModels - 开始查询工序");
            // 获取所有工序
            $processes = Db::name('scanwork_process')
                ->where('status', 1)
                ->order('name')
                ->select();
                
            error_log("getOrderModels - 查询到工序数量: " . count($processes));
            
            error_log("getOrderModels - 开始处理数据");
            $result = [];
            foreach ($orderModels as $orderModel) {
                error_log("getOrderModels - 处理订单型号: " . json_encode($orderModel));
                foreach ($processes as $process) {
                    error_log("getOrderModels - 处理工序: " . json_encode($process));
                    // 检查是否有该产品型号和工序的工价设置
                    $processPrice = Db::name('scanwork_process_price')->where([
                        'model_id' => $orderModel['model_id'],
                        'process_id' => $process['id']
                    ])->find();
                    
                    error_log("getOrderModels - 工价查询结果: " . json_encode($processPrice));
                    
                    if ($processPrice) {
                        error_log("getOrderModels - 开始获取产品信息");
                        // 获取产品信息
                        $model = Db::name('scanwork_model')->where('id', $orderModel['model_id'])->find();
                        $product = Db::name('scanwork_product')->where('id', $model['product_id'])->find();
                        
                        error_log("getOrderModels - 型号信息: " . json_encode($model));
                        error_log("getOrderModels - 产品信息: " . json_encode($product));
                        
                        $result[] = [
                            'model_id' => $orderModel['model_id'],
                            'model_name' => $model['name'],
                            'product_name' => $product['name'],
                            'process_id' => $process['id'],
                            'process_name' => $process['name'],
                            'order_quantity' => $orderModel['quantity'],
                            'piece_price' => $processPrice['price'],
                            'time_price' => $processPrice['time_price'],
                            'display_name' => $product['name'] . ' - ' . $model['name'] . ' (' . $process['name'] . ')'
                        ];
                        error_log("getOrderModels - 添加结果项: " . json_encode(end($result)));
                    }
                }
            }

            error_log("getOrderModels - 最终结果数量: " . count($result));
            return json(['code' => 1, 'msg' => '获取成功', 'data' => $result]);
        } catch (Exception $e) {
            $errorMsg = '获取订单型号失败：' . $e->getMessage();
            error_log("getOrderModels - 异常: " . $e->getMessage());
            error_log("getOrderModels - 异常堆栈: " . $e->getTraceAsString());
            return json(['code' => 0, 'msg' => $errorMsg, 'data' => null]);
        } catch (\Throwable $e) {
            $errorMsg = '获取订单型号失败：' . $e->getMessage();
            error_log("getOrderModels - Throwable异常: " . $e->getMessage());
            error_log("getOrderModels - Throwable异常堆栈: " . $e->getTraceAsString());
            return json(['code' => 0, 'msg' => $errorMsg, 'data' => null]);
        }
    }



    /**
     * 获取工序工价信息
     */
    public function getProcessPrice()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $model_id = $this->request->get('model_id');
        $process_id = $this->request->get('process_id');
        
        if (!$model_id || !$process_id) {
            $this->error('参数错误');
        }
        
        try {
            $processPrice = Db::name('scanwork_process_price')->where([
                'model_id' => $model_id,
                'process_id' => $process_id
            ])->find();
            
            if (!$processPrice) {
                $this->error('该产品型号和工序的工价未设置');
            }
            
            $this->success('获取成功', [
                'price' => floatval($processPrice['price']),
                'time_price' => floatval($processPrice['time_price'])
            ]);
        } catch (Exception $e) {
            $this->error('获取工价信息失败：' . $e->getMessage());
        }
    }

    /**
     * 获取订单信息
     */
    public function getOrderInfo()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $order_id = $this->request->get('order_id');
        if (!$order_id) {
            $this->error('参数错误');
        }
        
        try {
            $order = Db::name('scanwork_order')->where('id', $order_id)->find();
            if (!$order) {
                $this->error('订单不存在');
            }
            
            // 计算已分配数量
            $allocatedQuantity = Db::name('scanwork_allocation')
                ->where('order_id', $order_id)
                ->sum('quantity');
            
            // 计算已报工数量
            $reportedQuantity = Db::name('scanwork_report')
                ->alias('r')
                ->join('scanwork_allocation a', 'r.allocation_id = a.id')
                ->where('a.order_id', $order_id)
                ->where('r.status', 1)
                ->sum('r.quantity');
            
            $this->success('获取成功', [
                'total_quantity' => $order['total_quantity'],
                'allocated_quantity' => $allocatedQuantity,
                'available_quantity' => max(0, $order['total_quantity'] - $allocatedQuantity - $reportedQuantity)
            ]);
        } catch (Exception $e) {
            $this->error('获取订单信息失败：' . $e->getMessage());
        }
    }

    /**
     * 获取主动报工记录
     */
    public function getActiveReports()
    {
        if (!$this->auth->isLogin()) {
            return json(['code' => 0, 'msg' => '未登录', 'data' => null]);
        }
        
        $workerId = $this->auth->id;
        $page = intval($this->request->get('page', 1));
        $limit = intval($this->request->get('limit', 10));
        
        try {
            $offset = ($page - 1) * $limit;
            
            // 获取主动报工记录
            $reports = Db::name('scanwork_active_report')
                ->alias('ar')
                ->join('scanwork_order o', 'ar.order_id = o.id')
                ->join('scanwork_model m', 'ar.model_id = m.id')
                ->join('scanwork_product p', 'm.product_id = p.id')
                ->join('scanwork_process pr', 'ar.process_id = pr.id')
                ->where('ar.user_id', $workerId)
                ->field('ar.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
                ->order('ar.createtime desc')
                ->limit($offset, $limit)
                ->select();
            
            // 获取总数
            $total = Db::name('scanwork_active_report')
                ->where('user_id', $workerId)
                ->count();
            
            // 处理每条记录
            foreach ($reports as &$report) {
                $report['createtime_text'] = date('Y-m-d H:i:s', $report['createtime']);
                $report['status_text'] = $this->getStatusText($report['status']);
                
                // 获取图片数量
                $imageCount = Db::name('scanwork_active_report_product_item')
                    ->where('active_report_id', $report['id'])
                    ->count();
                $report['image_count'] = $imageCount;
            }
            
            return json([
                'code' => 1, 
                'msg' => '获取成功', 
                'data' => [
                    'list' => $reports,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit
                ]
            ]);
            
        } catch (Exception $e) {
            return json(['code' => 0, 'msg' => '获取主动报工记录失败：' . $e->getMessage(), 'data' => null]);
        }
    }

    /**
     * 获取主动报工详情
     */
    public function getActiveReportDetail()
    {
        if (!$this->auth->isLogin()) {
            return json(['code' => 0, 'msg' => '未登录', 'data' => null]);
        }
        
        $workerId = $this->auth->id;
        $reportId = intval($this->request->get('id'));
        
        if (!$reportId) {
            return json(['code' => 0, 'msg' => '参数错误', 'data' => null]);
        }
        
        try {
            // 获取报工详情
            $report = Db::name('scanwork_active_report')
                ->alias('ar')
                ->join('scanwork_order o', 'ar.order_id = o.id')
                ->join('scanwork_model m', 'ar.model_id = m.id')
                ->join('scanwork_product p', 'm.product_id = p.id')
                ->join('scanwork_process pr', 'ar.process_id = pr.id')
                ->where('ar.id', $reportId)
                ->where('ar.user_id', $workerId)
                ->field('ar.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
                ->find();
            
            if (!$report) {
                return json(['code' => 0, 'msg' => '报工记录不存在', 'data' => null]);
            }
            
            $report['createtime_text'] = date('Y-m-d H:i:s', $report['createtime']);
            $report['status_text'] = $this->getStatusText($report['status']);
            
            // 获取产品编号和图片
            $productItems = Db::name('scanwork_active_report_product_item')
                ->where('active_report_id', $reportId)
                ->field('item_no, image_url')
                ->select();
            
            // 按产品编号分组图片
            $groupedItems = [];
            foreach ($productItems as $item) {
                $itemNo = $item['item_no'];
                if (!isset($groupedItems[$itemNo])) {
                    $groupedItems[$itemNo] = [
                        'item_no' => $itemNo,
                        'images' => []
                    ];
                }
                $groupedItems[$itemNo]['images'][] = $item['image_url'];
            }
            
            $report['product_items'] = array_values($groupedItems);
            
            return json(['code' => 1, 'msg' => '获取成功', 'data' => $report]);
            
        } catch (Exception $e) {
            return json(['code' => 0, 'msg' => '获取报工详情失败：' . $e->getMessage(), 'data' => null]);
        }
    }

    /**
     * 获取状态文本
     */
    private function getStatusText($status)
    {
        switch ($status) {
            case 0:
                return '待审核';
            case 1:
                return '已通过';
            case 2:
                return '已拒绝';
            default:
                return '未知';
        }
    }

    /**
     * 获取消息列表
     */
    public function getMessages()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $userId = $user['id'];
        
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $type = $this->request->get('type', ''); // 消息类型筛选
        
        $where = ['user_id' => $userId];
        if ($type) {
            $where['type'] = $type;
        }
        
        $list = Db::name('scanwork_message')
            ->where($where)
            ->order('createtime desc')
            ->paginate($limit, false, ['page' => $page]);
            
        $items = $list->items();
        foreach ($items as &$item) {
            $item['createtime_text'] = date('Y-m-d H:i:s', $item['createtime']);
            $item['is_read_text'] = $item['is_read'] ? '已读' : '未读';
        }
        
        $this->success('获取成功', [
            'total' => $list->total(),
            'list' => $items
        ]);
    }

    /**
     * 获取未读消息数量
     */
    public function getUnreadMessageCount()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $userId = $user['id'];
        
        $count = Db::name('scanwork_message')
            ->where('user_id', $userId)
            ->where('is_read', 0)
            ->count();
        
        $this->success('获取成功', ['count' => $count]);
    }

    /**
     * 标记消息为已读
     */
    public function markMessageRead()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $userId = $user['id'];
        
        $messageId = $this->request->post('message_id');
        $markAll = $this->request->post('mark_all', 0); // 是否标记所有消息为已读
        
        if ($markAll) {
            // 标记所有消息为已读
            $result = Db::name('scanwork_message')
                ->where('user_id', $userId)
                ->where('is_read', 0)
                ->update(['is_read' => 1, 'readtime' => time()]);
            
            $this->success('标记成功', ['updated_count' => $result]);
        } else {
            // 标记单个消息为已读
            if (!$messageId) {
                $this->error('参数错误');
            }
            
            $result = Db::name('scanwork_message')
                ->where('id', $messageId)
                ->where('user_id', $userId)
                ->update(['is_read' => 1, 'readtime' => time()]);
            
            if ($result) {
                $this->success('标记成功');
            } else {
                $this->error('消息不存在或已标记为已读');
            }
        }
    }

    /**
     * 删除消息
     */
    public function deleteMessage()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $userId = $user['id'];
        
        $messageId = $this->request->post('message_id');
        $deleteAll = $this->request->post('delete_all', 0); // 是否删除所有已读消息
        
        if ($deleteAll) {
            // 删除所有已读消息
            $result = Db::name('scanwork_message')
                ->where('user_id', $userId)
                ->where('is_read', 1)
                ->delete();
            
            $this->success('删除成功', ['deleted_count' => $result]);
        } else {
            // 删除单个消息
            if (!$messageId) {
                $this->error('参数错误');
            }
            
            $result = Db::name('scanwork_message')
                ->where('id', $messageId)
                ->where('user_id', $userId)
                ->delete();
            
            if ($result) {
                $this->success('删除成功');
            } else {
                $this->error('消息不存在');
            }
        }
    }

    /**
     * 获取最新消息（用于首页显示）
     */
    public function getLatestMessages()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $userId = $user['id'];
        
        $limit = $this->request->get('limit', 5);
        
        $messages = Db::name('scanwork_message')
            ->where('user_id', $userId)
            ->order('createtime desc')
            ->limit($limit)
            ->select();
            
        foreach ($messages as &$message) {
            $message['createtime_text'] = date('Y-m-d H:i:s', $message['createtime']);
            $message['is_read_text'] = $message['is_read'] ? '已读' : '未读';
        }
        
        $this->success('获取成功', $messages);
    }

    /**
     * 更新订阅消息状态
     */
    public function updateSubscribeStatus()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $userId = $user['id'];
        $subscribeResult = $this->request->post('subscribe_result');
        
        if (!$subscribeResult) {
            $this->error('参数错误');
        }
        
        // 更新用户的订阅状态
        $updateData = [
            'subscribe_allocation' => isset($subscribeResult['your_allocation_template_id']) && $subscribeResult['your_allocation_template_id'] === 'accept' ? 1 : 0,
            'subscribe_audit' => isset($subscribeResult['your_audit_template_id']) && $subscribeResult['your_audit_template_id'] === 'accept' ? 1 : 0,
            'updatetime' => time()
        ];
        
        $result = Db::name('user')->where('id', $userId)->update($updateData);
        
        if ($result !== false) {
            $this->success('订阅状态更新成功');
        } else {
            $this->error('订阅状态更新失败');
        }
    }
} 